package com.dmgis.hndz.common.utils;


import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.stream.IntStream;


public class WordToPdfConverter {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://192.168.0.32:91/0fda37b7063e458d8906e05a1e80066c.doc");
        URL url2 = new URL("http://192.168.0.32:91/0fda37b7063e458d8906e05a1e80066c.pdf");
        File inputWord = new File(String.valueOf(url));
        File outputFile = new File(String.valueOf(url2));
        try  {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
//            IConverter converter = LocalConverter.builder().build();
            IntStream LocalConverter = null;
            IConverter converter = (IConverter) IntStream.builder().build();
            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String  WordToPdfConverter(String in , String out) {

        try {
            // 读取Word文档
            XWPFDocument doc = new XWPFDocument(new FileInputStream(in));

            // 创建PDF文档
            PDDocument pdf = new PDDocument();
            PDPage page = new PDPage();
            pdf.addPage(page);

            // 创建PDF内容流
            PDPageContentStream contentStream = new PDPageContentStream(pdf, page);

            File outFile = new File(out);
            String fontpath = outFile.getParentFile() + "\\Documents\\fonts\\simfang.ttf";
            PDFont font = PDType0Font.load(pdf, new File(fontpath));

            // 从Word文档读取内容并写入PDF文档
            for (XWPFParagraph paragraph : doc.getParagraphs()) {
                contentStream.beginText();
                contentStream.setFont(font, 12);
                contentStream.newLineAtOffset(25, 700);
                contentStream.showText(paragraph.getText());
                contentStream.endText();
            }

            // 关闭内容流
            contentStream.close();

            // 保存PDF文档
            pdf.save(new FileOutputStream(out));
            pdf.close();
            doc.close();

            System.out.println("转换成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out;
    }
}

